﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinServer
{
    public class FrmMain : Form
    {
        private GroupBox groupBox1;
        private TextBox txtPort;
        private Button btnStart;
        private RichTextBox richTextBox1;
        private TextBox txtIPString;
        private Button btnSend;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.txtIPString = new System.Windows.Forms.TextBox();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.btnSend);
            this.groupBox1.Controls.Add(this.txtIPString);
            this.groupBox1.Controls.Add(this.txtPort);
            this.groupBox1.Controls.Add(this.btnStart);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.groupBox1.Location = new System.Drawing.Point(0, 0);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(584, 48);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            // 
            // txtIPString
            // 
            this.txtIPString.Location = new System.Drawing.Point(12, 21);
            this.txtIPString.Name = "txtIPString";
            this.txtIPString.Size = new System.Drawing.Size(100, 21);
            this.txtIPString.TabIndex = 2;
            this.txtIPString.Text = "127.0.0.1";
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(118, 21);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(100, 21);
            this.txtPort.TabIndex = 1;
            this.txtPort.Text = "18099";
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(224, 19);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 0;
            this.btnStart.Text = "启动";
            this.btnStart.UseVisualStyleBackColor = true;
            // 
            // richTextBox1
            // 
            this.richTextBox1.BackColor = System.Drawing.SystemColors.Info;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(0, 48);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ReadOnly = true;
            this.richTextBox1.Size = new System.Drawing.Size(584, 413);
            this.richTextBox1.TabIndex = 1;
            this.richTextBox1.Text = "";
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(305, 19);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(75, 23);
            this.btnSend.TabIndex = 3;
            this.btnSend.Text = "发送";
            this.btnSend.UseVisualStyleBackColor = true;
            // 
            // FrmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(584, 461);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.groupBox1);
            this.Name = "FrmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        public FrmMain()
        {
            InitializeComponent();

            this.Load += FrmMain_Load;
        }
        
        TcpSocketServer _Server = null;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.btnStart.Click += BtnStart_Click;
            this.btnSend.Click += BtnSend_Click;
            this.FormClosing += FrmMain_FormClosing;
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            //this._Server.SendTo("127.0.0.1", 8080, System.Text.Encoding.UTF8.GetBytes("hi"));
            Task.Factory.StartNew(() =>
            {
                try
                {
                    using (UDPSocket udp = new UDPSocket(this.txtIPString.Text.Trim(), int.Parse(this.txtPort.Text)))
                    {
                        udp.Socket.ReceiveTimeout = 10 * 1000;

                        //udp.SendTo("127.0.0.1", 8080, System.Text.Encoding.UTF8.GetBytes("hi"));
                        //udp.SendToAsync("127.0.0.1", 8080, System.Text.Encoding.UTF8.GetBytes("hi"));

                        //Task task = new Task(() => {

                        //});
                        //task.Start();
                        //task.Wait();

                        IPEndPoint remote = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8088);
                        udp.SendTo(remote, System.Text.Encoding.UTF8.GetBytes("hi"));

                        byte[] buffer = new byte[10 * 1024];
                        EndPoint any = new IPEndPoint(IPAddress.Any, 0);
                        //SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                        //args.RemoteEndPoint = remote;
                        //args.Completed += Args_Completed;
                        //udp.ReceiveFromAsync(args);
                        int count = udp.ReceiveFrom(buffer, ref any);
                        if (count <= 0)
                        {
                            MessageBox.Show("未能收到返回内容！");
                        }
                        else
                        {
                            string data = System.Text.Encoding.Default.GetString(buffer, 0, count);
                            MessageBox.Show("返回结果：" + data);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("发送数据异常：" + ex.ToString());
                }
            });

            
        }

        private void Args_Completed(object sender, SocketAsyncEventArgs e)
        {
            if(e.Buffer == null || e.Buffer.Length <= 0)
            {
                MessageBox.Show("未能收到返回内容！");
            }
            else
            {
                string data = System.Text.Encoding.Default.GetString(e.Buffer);
                MessageBox.Show("返回结果：" + data);
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this._Server != null)
                this._Server.Dispose();
        }

        private void BtnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if(this.btnStart.Text == "启动")
                {
                    if (this.txtIPString.Text.Trim() == "")
                    {
                        this.txtIPString.Focus();
                        return;
                    }
                    if (this.txtPort.Text.Trim() == "")
                    {
                        this.txtPort.Focus();
                        return;
                    }
                    this._Server = new TcpSocketServer();
                    if (this._Server.Start(this.txtIPString.Text.Trim(),int.Parse(this.txtPort.Text)) == false)
                        return;

                    this.txtIPString.ReadOnly = true;
                    this.txtIPString.BackColor = System.Drawing.SystemColors.Info;
                    this.txtPort.ReadOnly = true;
                    this.txtPort.BackColor = System.Drawing.SystemColors.Info;

                    this.btnStart.Text = "暂停";
                }
                else
                {
                    this._Server.Close();

                    this.btnStart.Text = "启动";
                    this.txtIPString.ReadOnly = false;
                    this.txtIPString.BackColor = System.Drawing.SystemColors.Window;
                    this.txtPort.ReadOnly = false;
                    this.txtPort.BackColor = System.Drawing.SystemColors.Window;
                }
            }
            finally
            {
                this.btnStart.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }
    }
}
